﻿
using System;
using System.Collections.Generic;

using Bootstrap5.Abstractions;

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;

namespace Bootstrap5;

[CssClass("form-check-input")]
public class FormInputCheckbox:FormInputBase<bool>
{
    [CascadingParameter] FormInputGroup CascadedInputGroup { get; set; }
    [Parameter] public bool Inline { get; set; }
    [Parameter] public bool Switch { get; set; }
	[Parameter] public RenderFragment ChildContent { get; set; }
	protected override string Type => "checkbox";

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        if (CascadedInputGroup is null)
        {
            builder.OpenElement(0, "div");
            builder.AddAttribute(1, "class", GetFormCheckClass());

            builder.AddContent(10, content =>
            {
                BuildInput(content);
                BuildLabel(content);
                BuildFeedback(content);
            });
            builder.CloseElement();
        }
        else
        {
            BuildInput(builder);
            BuildLabel(builder);
        }
    }

	private void BuildFeedback(RenderTreeBuilder builder)
	{
        if(ChildContent is not null)
		{
            builder.OpenRegion(300);
            builder.AddContent(0, ChildContent);
            builder.CloseRegion();
        }
	}

	protected override void BuildInput(RenderTreeBuilder builder)
    {
        builder.OpenRegion(100);
        builder.OpenElement(0, GetHtmlTagName());
        builder.AddAttribute(1, "type", Type);
        builder.AddAttribute(2, "id", FieldId);
        builder.AddAttribute(3, "checked", CurrentValue);
        builder.AddAttribute(4, "name", FieldIdentifier.FieldName);
        builder.AddAttribute(5, ChangeEvent.Value, EventCallback.Factory.CreateBinder(this, __value => CurrentValue = __value, CurrentValue));
        BuildCommonAttributes(builder);
        builder.CloseElement();
        builder.CloseRegion();
    }

    protected override void BuildLabel(RenderTreeBuilder builder)
    {
        if (!AutoLabel)
        {
            return;
        }
        if (string.IsNullOrEmpty(DisplayName))
        {
            return;
        }
        builder.OpenElement(0,"label");
        builder.AddAttribute(1, "for", FieldId);
        builder.AddAttribute(2, "class", "form-check-label");
        builder.AddContent(10, DisplayName);
        builder.CloseElement();
    }
    string GetFormCheckClass()
    {
        var list = new List<string>() { "form-check" };
        if (Inline)
        {
            list.Add("form-check-inline");
        }
        if (Switch)
        {
            list.Add("form-switch");
        }
        return string.Join(" ", list);
    }
}
